import CryptoJS from 'crypto-js'
const key: string = CryptoJS.enc.Utf8.parse('ASNCHEYB3489UH44')  // 十六位十六进制数作为密钥
const iv: string = CryptoJS.enc.Utf8.parse('savvying^ss^ss')   //
const local = window.localStorage

// 加密方法
function Encrypt (word: any): any {
  const srcs: any = CryptoJS.enc.Utf8.parse(word)
  const encrypted: any = CryptoJS.AES.encrypt(srcs, key, { iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 })
  return encrypted.ciphertext.toString().toUpperCase()
}

// 解密方法
function Decrypt (word: any): any {
  const encryptedHexStr: any = CryptoJS.enc.Hex.parse(word)
  const srcs: any = CryptoJS.enc.Base64.stringify(encryptedHexStr)
  const decrypt: any = CryptoJS.AES.decrypt(srcs, key, { iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 })
  const decryptedStr: any = decrypt.toString(CryptoJS.enc.Utf8)
  return decryptedStr.toString()
}

export default {
  set (name: any, value: any): void {
    if (typeof(value) === 'object') {
      value = Encrypt(JSON.stringify(value))
    } else {
      value = Encrypt(JSON.stringify({ myCacheValue: value }))
    }
    local.setItem(name, value)
  },
  get (name: any) {
    const item: any = local.getItem(name)
    if (!item) {
      return null
    }
    const obj: any = JSON.parse(Decrypt(item))
    if (obj.myCacheValue) {
      return obj.myCacheValue
    }
    return obj
  },
  clear (name: any) {
    if (name) {
      local.removeItem(name)
    } else {
      local.clear()
    }
  }
}


